package GearCommands;

import Connections.DownloaderClient;
import Connections.Peer;
import Gear.Factory;
import Gear.Gear;

import java.io.File;
import java.nio.file.FileSystems;

/**
 * Implementation of the user command movx.
 * Request an external file to the local gear path.
 *
 * @author Rodrigo Martins Racanicci
 */
public class GearCommandMovX implements GearCommand {

    @Override
    public void execute(String[] args, Gear gear) {
        try {
            if (args.length < 2) throw new IllegalArgumentException("Too few arguments to movx command.");

            File f;

            if ((f = FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), args[1].trim()).toFile()).exists()) {
                System.out.println("Error: There is already a file with this name at the local machine!");
                return;
            }

            String peer = Peer.getInstance().requestPeer(args[1]);

            if (peer.equals("null")) {
                System.out.println("Error: This file doesnt exist anymore!");
                return;
            }

            Factory.getInstance().getLocalFileMutex().acquire(args[1].trim());
            new DownloaderClient(peer).dowload(args[1].trim());
            f.setReadOnly();
            Factory.getInstance().getLocalFileMutex().release(args[1].trim());
            Peer.getInstance().sycronizeSharedFolder().send();

        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }

}
